package com.gzdh.tang.modu.controller;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.gzdh.tang.comm.util.ObjectUtil;
import com.gzdh.tang.comm.vo.Result;
import com.gzdh.tang.modu.dto.DInStockKuCunDto;
import com.gzdh.tang.modu.entity.Fk;
import com.gzdh.tang.modu.entity.Reserve;
import com.gzdh.tang.modu.entity.TangDevice;
import com.gzdh.tang.modu.mapper.MPublicMapper;
import com.gzdh.tang.modu.model.FoodsModel;
import com.gzdh.tang.modu.model.OrderProductModel;
import com.gzdh.tang.modu.model.ProductModel;
import com.gzdh.tang.modu.service.FkService;
import com.gzdh.tang.modu.service.ReserveService;
import com.gzdh.tang.modu.service.TangDeviceService;
import com.gzdh.tang.warehouse.entity.InStock;
import com.gzdh.tang.warehouse.service.InStockService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

@Slf4j
@RestController
@RequestMapping("api/depot")
public class DepotController {

    @Autowired
    MPublicMapper mapper;

    @Autowired
    InStockService inStockService;

    @Autowired
    TangDeviceService tangDeviceService;

    @Autowired
    ReserveService reserveService;


    @Autowired
    FkService fkService;

    @GetMapping("getProduct")
    public Result<Object> getProduct(@RequestParam("posnum") String posnum) {
        Result<Object> result = new Result<>();
        TangDevice tangDevice = tangDeviceService.getOne(new QueryWrapper<TangDevice>().lambda().eq(TangDevice::getPosnum, posnum));
        if (tangDevice == null) {
            return Result.error("获取失败");
        }
        List<ProductModel> productModelList = mapper.findProduct(tangDevice.getCkId());
        List<DInStockKuCunDto> dInStockKuCunDtos = mapper.getDInStockKuCun(tangDevice.getAddr(), tangDevice.getCkId());
        List<Map<String, Object>> phRecords = mapper.getPhRecord(tangDevice.getAddr(), tangDevice.getCkId());
        List<ProductModel> resProductModel = new ArrayList<>();
        for (ProductModel goo : productModelList) {
            List<ProductModel.Device> deviceList = new ArrayList<>();
            for (ProductModel.Device goo1 : goo.getDeviceList()) {
                DInStockKuCunDto dto = dInStockKuCunDtos.stream().filter(dInStockKuCunDto -> dInStockKuCunDto.getDeviceid()
                        .equals(goo1.getDeviceID())).findFirst().orElse(null);
                if (dto != null) {
                    goo1.setPriceVer(dto.getPriceVer());
                    goo1.setNumber(new BigDecimal(dto.getNumber()));
                    goo1.setSale_price(dto.getSalePrice());
                    goo1.setPid(dto.getPid());
                    goo1.setProvider(dto.getProvider());
                    goo1.setPriceAdjustTimes(dto.getPriceAdjustTimes());
                    Map<String, Object> deviceMap = phRecords.stream()
                            .filter(v -> ObjectUtil.getStr(v.get("deviceId")).equals(ObjectUtil.getStr(goo1.getDeviceID())))
                            .filter(v -> ObjectUtil.getStr(v.get("priceVer")).equals(ObjectUtil.getStr(goo1.getPriceVer())))
                            .findFirst().orElse(null);
                    if(deviceMap != null) {
                        BigDecimal number = ObjectUtil.getBigDecimal(deviceMap.get("number"));
                        goo1.setNumber(ObjectUtil.getBigDecimal(goo1.getNumber()).add(number));
                    }
                    if(goo1.getNumber().compareTo(new BigDecimal(0)) > 0) {
                        deviceList.add(goo1);
                    }
                }
            }
            if (deviceList.size() > 0) {
                ProductModel productModel = new ProductModel();
                productModel.setClsid(goo.getClsid());
                productModel.setClsname(goo.getClsname());
                productModel.setDeviceList(deviceList);
                resProductModel.add(productModel);
            }
        }
        result.setResult(resProductModel);
        return result;
    }


    @GetMapping("order")
    public Result<Object> getOrder(@RequestParam("posnum") String posnum) {
        Result<Object> result = new Result<>();
        String timeSdf = new SimpleDateFormat("yyyy-MM-dd").format(new Date());
        List<OrderProductModel> orderProductModelList = mapper
                .getOrderProduct(timeSdf + " 00:00:00", timeSdf + " 23:59:59", posnum);
        for (OrderProductModel goo : orderProductModelList) {
            BigDecimal price = new BigDecimal(0);
            BigDecimal count = new BigDecimal(0);
            for (OrderProductModel.Product product : goo.getProductList()) {
                price = price.add(product.getNumber().multiply(product.getPrice()));
                count = count.add(product.getNumber());
            }
            goo.setAmountCount(count);
            goo.setAmountPrice(price);
        }
        result.setResult(orderProductModelList);
        return result;
    }


    @PostMapping("tuikuoOrder")
    public Result<Object> tuikuoOrders(@RequestBody JSONObject jsonObject) {
        System.out.println(jsonObject.toJSONString());
        Result<Object> result = new Result<>();
        String posnum = jsonObject.getString("posnum");
        List<FoodsModel> foodsModelList = jsonObject.getJSONArray("tuikuiFoods").toJavaList(FoodsModel.class);
        TangDevice tangDevice = tangDeviceService.getOne(new QueryWrapper<TangDevice>().lambda().eq(TangDevice::getPosnum, posnum));
        int tempi = 0;
        Date date = new Date();
        List<Reserve> reserveList = reserveService.list(new QueryWrapper<Reserve>().lambda()
                .eq(Reserve::getZfserialnumber, foodsModelList.get(0).getDh()));

        for (FoodsModel goo : foodsModelList) {
            tempi++;
            try {
                InStock inStock = inStockService.getOne(new QueryWrapper<InStock>()
                        .lambda().eq(InStock::getDh, goo.getDh())
                        .eq(InStock::getDeviceid, goo.getDeviceId())
                        .ge(InStock::getNumber, 0));
                inStock.setNumber(new BigDecimal(goo.getNumber()));

                inStock.setId(null);
                inStockService.save(inStock);
                //写RESERVE
                Reserve reserve = new Reserve();
                reserve.setCardno(inStock.getCardno());
                reserve.setZl(tangDevice.getZl());
                reserve.setBqh(tangDevice.getBqh());
                reserve.setKsh(tangDevice.getKsh());
                reserve.setBed("0");
                reserve.setPosnum(tangDevice.getPosnum());
                reserve.setDinner(tangDevice.getDinner());
                reserve.setCode(tangDevice.getCode());
                reserve.setSl(inStock.getNumber().intValue());
                reserve.setJe(inStock.getNumber().multiply(inStock.getSalePrice()).stripTrailingZeros()
                        .toPlainString());
                reserve.setYe("0");
                reserve.setKl(reserveList.get(0).getKl());
                reserve.setSc(reserveList.get(0).getSc());
                reserve.setLsh2(inStock.getDh());
                reserve.setCzrq(new Date(date.getTime() + (tempi * 10)));
                reserve.setDcrq(new SimpleDateFormat("yyyy-MM-dd 00:00:00").format(new Date()));
                reserve.setHname(inStock.getDevicename());
                reserve.setSddz(inStock.getDh());
                reserve.setCs(0);
                reserve.setKehu("");
                reserve.setZfserialnumber(inStock.getDh());
                reserve.setAddr(tangDevice.getAddr());
                reserveService.save(reserve);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return result;
    }

    @GetMapping("getFk")
    public Result<Object> getFk(@RequestParam("cardsn") String cardsn) {
        Result<Object> result = new Result<>();
        Fk fk = fkService.getOne(new QueryWrapper<Fk>().lambda().eq(Fk::getCardsn, cardsn));
        result.setResult(fk);
        return result;
    }


}
